/****
 * not-doc
 * @see com.smforj.ssm.sys.web.controller.UploadController
 * 
 * @author ghj
 */
package com.smforj.ssm.sys.web.controller.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.smforj.ssm.frame.core.web.domain.DataResult;
import com.smforj.ssm.frame.core.web.domain.DataResult.DataStatus;
import com.smforj.ssm.sys.web.controller.UploadController;
import com.smforj.ssm.util.PropKit;

/***
 * 共用上传实现类
 * 
 * @author Haijun Gao 
 * @date 2016-9-8 上午10:22:39
 * @desp http://www.cnblogs.com/saga5998/
 * @email 573107773@qq.com
 */ 
@Controller
@RequestMapping(value={"/upload"})
public class UploadControllerImpl implements UploadController{
	
	private Logger log = Logger.getLogger(UploadControllerImpl.class);

	/****
	 * not-doc
	 * @see com.smforj.ssm.sys.web.controller.UploadController#fileUploadStream
	 * 
	 * @author ghj
	 */
	@Override
	@RequestMapping("/fileStream")
	public DataResult<String> fileUploadStream(CommonsMultipartFile file)
			throws IOException { 
	    //用来检测程序运行时间
        long  startTime=System.currentTimeMillis();
        log.info("fileName："+file.getOriginalFilename());
        String fileName = file.getOriginalFilename();
        DataResult<String> result = new DataResult<String>();
        try {
        	String savePath = getFilePath(file.getOriginalFilename());
            //获取输出流
            OutputStream os=new FileOutputStream(savePath);
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is=file.getInputStream();
            int temp;
            //一个一个字节的读取并写入
            while((temp=is.read())!=(-1))
            {
                os.write(temp);
            }
           os.flush();
           os.close();
           is.close();
         
        } catch (FileNotFoundException e) { 
        	result.setStatus(DataStatus.ERROR);
        	result.setMessage("upload error!");
            e.printStackTrace();
        }
        long  endTime=System.currentTimeMillis();
        log.info("fileUploadStream 运行时间："+String.valueOf(endTime-startTime)+"ms"); 
        result.setStatus(DataStatus.OK);
        result.setData(fileName);
        return result;  
	}

	/****
	 * not-doc
	 * @see com.smforj.ssm.sys.web.controller.UploadController#fileUploadTransto
	 * 
	 * @author ghj
	 */
	@Override
	@RequestMapping("/fileTransto")
	public DataResult<String> fileUploadTransto(@RequestParam("file") CommonsMultipartFile file)
			throws IOException {  
	    long  startTime=System.currentTimeMillis();
	    String fileName = file.getOriginalFilename();
        System.out.println("fileName："+file.getOriginalFilename());
        DataResult<String> result = new DataResult<String>();
        String path= getFilePath(file.getOriginalFilename()); 
        log.info("save path: "+path);
        File newFile=new File(path); 
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(newFile);
        long  endTime=System.currentTimeMillis();
        System.out.println("fileUploadTransto 运行时间："+String.valueOf(endTime-startTime)+"ms");
        result.setStatus(DataStatus.OK);
        result.setData(fileName);
		return result;
	}
	
	private String getFilePath(String fileName)
	{
		return PropKit.get("filePath")+new Date().getTime()+fileName;
	}

	/****
	 * not-doc
	 * @see com.smforj.ssm.sys.web.controller.UploadController#fileUploadSpring
	 * Recommended Use it's very flexible!!!
	 * @author ghj
	 */
	@Override
	@RequestMapping("fileSpring")
	public DataResult<String> fileUploadSpring(HttpServletRequest request)
			throws IllegalStateException, IOException { 
        long  startTime=System.currentTimeMillis();
        String fileName = "";
        DataResult<String> result = new DataResult<String>();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
       CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
               request.getSession().getServletContext());
       //检查form中是否有enctype="multipart/form-data"
       if(multipartResolver.isMultipart(request))
       {
           //将request变成多部分request
           MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
          //获取multiRequest 中所有的文件名
           Iterator<String> iter=multiRequest.getFileNames(); 
           while(iter.hasNext())
           {
               //一次遍历所有文件
               MultipartFile file=multiRequest.getFile(iter.next().toString());
               if(file!=null)
               {
            	   fileName = file.getOriginalFilename();
                   String path=getFilePath(fileName);
                   //上传
                   file.transferTo(new File(path));
               }
                
           }
          
       }
       long  endTime=System.currentTimeMillis();
       System.out.println("fileUploadSpring 运行时间："+String.valueOf(endTime-startTime)+"ms");
       result.setStatus(DataStatus.OK);
       result.setData(fileName);
	   return result;
	}  

}
